package com.example.order_engine.domain.model;

import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单聚合根
 */
@Entity
@Table(name = "orders")
public class Order {
    @Id
    private String orderId;
    
    @Column(nullable = false)
    private String orderType;
    
    @Column(nullable = false)
    private String customerId;
    
    @Column(nullable = false)
    private BigDecimal totalAmount;
    
    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private OrderStatus status;
    
    @Column(nullable = false)
    private LocalDateTime createTime;
    
    @Column(nullable = false)
    private LocalDateTime updateTime;
    
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "order_id")
    private List<OrderItem> items;
    
    @Embedded
    private OrderExtraInfo extraInfo;

    public Order(String orderId, String orderType, String customerId, 
                BigDecimal totalAmount, List<OrderItem> items, OrderExtraInfo extraInfo) {
        this.orderId = orderId;
        this.orderType = orderType;
        this.customerId = customerId;
        this.totalAmount = totalAmount;
        this.status = OrderStatus.CREATED;
        this.createTime = LocalDateTime.now();
        this.updateTime = LocalDateTime.now();
        this.items = items;
        this.extraInfo = extraInfo;
    }

    // 业务方法
    public void validate() {
        if (totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("订单金额必须大于0");
        }
        if (items == null || items.isEmpty()) {
            throw new IllegalArgumentException("订单必须包含商品");
        }
    }

    public void complete() {
        this.status = OrderStatus.COMPLETED;
        this.updateTime = LocalDateTime.now();
    }

    public void cancel() {
        this.status = OrderStatus.CANCELLED;
        this.updateTime = LocalDateTime.now();
    }

    // Getters
    public String getOrderId() { return orderId; }
    public String getOrderType() { return orderType; }
    public String getCustomerId() { return customerId; }
    public BigDecimal getTotalAmount() { return totalAmount; }
    public OrderStatus getStatus() { return status; }
    public LocalDateTime getCreateTime() { return createTime; }
    public LocalDateTime getUpdateTime() { return updateTime; }
    public List<OrderItem> getItems() { return items; }
    public OrderExtraInfo getExtraInfo() { return extraInfo; }
}